/**
 * 
 */
package cn.com.xf.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.com.xf.common.AbstractBaseController;
import cn.com.xf.common.Constants;
import cn.com.xf.common.StringUtil;
import cn.com.xf.domain.TblOaNotice;
import cn.com.xf.domain.TblSiteWeeklyArticle;
import cn.com.xf.domain.TblSiteWeeklyMap;
import cn.com.xf.domain.VDstarea;
import cn.com.xf.service.NoticeService;
import cn.com.xf.service.PushService;
import cn.com.xf.service.SmsService;
import cn.com.xf.service.WeeklyService;
import cn.com.xf.utils.encode.EncrypTool;
import cn.com.xf.web.PageModel;
import cn.com.xf.web.XFMappingJacksonJsonView;
import cn.com.xf.web.form.NoticeForm;
import cn.com.xf.web.security.UserInfo;

/**
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/notice")
public class NoticeController extends AbstractBaseController {
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private PushService pushService;
	@Autowired
	private WeeklyService weeklyService;
	@Autowired
	private SmsService smsService;

	@RequestMapping
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response, NoticeForm form)
			throws Exception {
		form.setTab(Constants.TAB_NOTICE);
		ModelAndView mv = new ModelAndView("/notice/index", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}

	@RequestMapping(value = "/step")
	public ModelAndView notice_step(HttpServletRequest request, HttpServletResponse response, NoticeForm form)
			throws Exception {
		String group = Constants.NOTICE_GROUP_NOTICE;
		if (StringUtils.isNotBlank(form.getGroup())) {
			if (Constants.NOTICE_GROUP_DAILY.equalsIgnoreCase(form.getGroup())) {
				group = Constants.NOTICE_GROUP_DAILY;
			}
		}
		ModelAndView mv = new ModelAndView("/notice/notice", Constants.FORM_COMMAND_KEY, form);
		form.setGroup(group);
		String title = StringUtil.StringFilter(form.getTitle());
		String page = StringUtil.StringFilter(form.getPageNum());
		form.setTitle(title);
		form.setPageNum(page);
		return mv;
	}

	@RequestMapping(value = "/list")
	public ModelAndView notice_list(HttpServletRequest request, HttpServletResponse response, NoticeForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/notice/notice_list", Constants.FORM_COMMAND_KEY, form);
		// 1.模糊搜索关键字
		String title = StringUtil.StringFilter(form.getTitle());
		String isimportant = StringUtil.StringFilter(form.getIsimportant());
		String istop = StringUtil.StringFilter(form.getIstop());
		String group = StringUtil.StringFilter(form.getGroup());
		String viceTitle = StringUtil.StringFilter(form.getViceTitle());
		
		form.setViceTitle(viceTitle);
		form.setTitle(title);
		form.setIsimportant(isimportant);
		form.setIstop(istop);
		form.setGroup(group);
		//查询员工所属一级中心站点
		UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String siteId = user.getSiteId();
		String centerId = "";
		if("10000".equals(siteId)){
			centerId = "10000";
		}else{
			centerId = noticeService.selectOfCenter(siteId);
		}
		
		// 2.总记录数
		int count = noticeService.selectNoticeCount(title, viceTitle, isimportant, istop, group, centerId);
		if (count == 0) {
			return mv;
		}

		// 3.分页信息
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();

		// 4.排序规则
		String orderByField = "PUBLIC_TIME";
		String orderByMode = "DESC";
		if (StringUtils.isNotBlank(form.getOrderByField()) && StringUtils.isNotBlank(form.getOrderByMode())) {
			if ("title".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "TITLE";
			}
			if ("deptId".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "PUBLIC_DEPART_ID";
			}
			if ("publicMan".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "PUBLIC_MAN";
			}
			if ("publicTime".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "PUBLIC_TIME";
			}
			if ("asc".equalsIgnoreCase(form.getOrderByMode()) || "desc".equalsIgnoreCase(form.getOrderByMode())) {
				orderByMode = form.getOrderByMode();
			}
		}
		// 5.查询
		List<TblOaNotice> list = noticeService.selectNotice(begin, pageSize, orderByField, orderByMode, title,
				viceTitle,isimportant, istop, group, centerId);
		mv.addObject("list", list);
		return mv;
	}

	@RequestMapping(value = "/manageList")
	public ModelAndView notice_managerlist(HttpServletRequest request, HttpServletResponse response, NoticeForm form)
			throws Exception {
		String group = StringUtil.StringFilter(form.getGroup());
		String view = "";
		if (Constants.NOTICE_GROUP_NOTICE.equalsIgnoreCase(group)) {
			view = "/notice/notice_manage_list_notice";
		} else if (Constants.NOTICE_GROUP_DAILY.equalsIgnoreCase(group)) {
			view = "/notice/notice_manage_list_daily";
		}
		ModelAndView mv = new ModelAndView(view, Constants.FORM_COMMAND_KEY, form);
		// 1.模糊搜索关键字
		String title = StringUtil.StringFilter(form.getTitle());
		String isimportant = StringUtil.StringFilter(form.getIsimportant());
		String istop = StringUtil.StringFilter(form.getIstop());
		String viceTitle = StringUtil.StringFilter(form.getViceTitle());
		
		form.setViceTitle(viceTitle);
		form.setTitle(title);
		form.setIsimportant(isimportant);
		form.setIstop(istop);
		form.setGroup(group);
		
		//查询员工所属一级中心站点
		UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String siteId = user.getSiteId();
		String centerId = "";
		if("10000".equals(siteId)){
			centerId = "10000";
		}else{
			centerId = noticeService.selectOfCenter(siteId);
		}
		
		// 2.总记录数
		int count = noticeService.selectNoticeCount(title,viceTitle, isimportant, istop, group, centerId);
		if (count == 0) {
			return mv;
		}

		// 3.分页信息
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();

		// 4.排序规则
		String orderByField = "PUBLIC_TIME";
		String orderByMode = "DESC";
		if (StringUtils.isNotBlank(form.getOrderByField()) && StringUtils.isNotBlank(form.getOrderByMode())) {
			if ("title".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "TITLE";
			}
			if ("deptId".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "PUBLIC_DEPART_ID";
			}
			if ("publicMan".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "PUBLIC_MAN";
			}
			if ("publicTime".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "PUBLIC_TIME";
			}
			if ("asc".equalsIgnoreCase(form.getOrderByMode()) || "desc".equalsIgnoreCase(form.getOrderByMode())) {
				orderByMode = form.getOrderByMode();
			}
		}

		// 5.查询
		List<TblOaNotice> list = noticeService.selectNotice(begin, pageSize, orderByField, orderByMode, title,
				viceTitle,isimportant, istop, group, centerId);
		mv.addObject("list", list);
		return mv;
	}

	/**
	 * 公告详情页
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/detail")
	public ModelAndView notice_detial(HttpServletRequest request, HttpServletResponse response, NoticeForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/notice/detail", Constants.FORM_COMMAND_KEY, form);
		String noticeIdStr = form.getNoticeId();
		String realNoticeId = "";
		if (StringUtils.isNotBlank(noticeIdStr)) {
			realNoticeId = EncrypTool.dencode(noticeIdStr);
		}
		TblOaNotice coreNotice = noticeService.selectNoticeById(new Integer(realNoticeId));

		String title = form.getTitle();
		String pageNum = form.getPageNum();
		String group = form.getGroup();
		form.setTitle(title);
		form.setPageNum(pageNum);
		form.setGroup(group);
		
		//查询员工所属一级中心站点
		UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String siteId = user.getSiteId();
		String centerId = "";
		if("10000".equals(siteId)){
			centerId = "10000";
		}else{
			centerId = noticeService.selectOfCenter(siteId);
		}
		
		// 2.获取上下条
		List<TblOaNotice> list = noticeService.selectPrevAndNextById(realNoticeId, coreNotice.getNoticeGroup(),centerId);
		if (!CollectionUtils.isEmpty(list)) {
			if (list.size() == 1) {
				TblOaNotice notice = list.get(0);
				if (notice.getNoticeId() > Long.valueOf(realNoticeId)) {
					mv.addObject("next", notice);
				} else if (notice.getNoticeId() < Long.valueOf(realNoticeId)) {
					mv.addObject("prev", notice);
				}
			} else if (list.size() == 2) {
				mv.addObject("prev", list.get(0));
				mv.addObject("next", list.get(1));
			}
		}

		// 3.插入读过的记录
		noticeService.insertNoticeRead(coreNotice.getNoticeId() + "", user.getUsername(), coreNotice.getNoticeGroup());

		// 4.返回
		mv.addObject("coreNotice", coreNotice);
		return mv;
	}

	/**
	 * 添加记录
	 */
	@RequestMapping(value = "/add")
	public ModelAndView notice_add(HttpServletRequest request, HttpServletResponse response, NoticeForm form)
			throws Exception {
		String view = "";
		ModelAndView mv = new ModelAndView(view, Constants.FORM_COMMAND_KEY, form);
		String group = form.getGroup();
		if (Constants.NOTICE_GROUP_NOTICE.equalsIgnoreCase(group)) {
			view = "/notice/add_notice";
			// 获取区域负责人的手机号码
			List<VDstarea> mobileList = noticeService.selectMobiles();
			mv.addObject("mobileList", mobileList);
		} else if (Constants.NOTICE_GROUP_DAILY.equalsIgnoreCase(group)) {
			view = "notice/add_daily";
		}
		//判断是否是总部账号
		//查询员工所属一级中心站点
		UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String siteId = user.getSiteId();
		String isCenter = "";
		if("10000".equals(siteId)){
			isCenter = "1";
		}else{
			String centerId = noticeService.selectOfCenter(siteId);
			if("769000".equals(centerId)){
				isCenter = "1";
			}
		}
		mv.addObject("isCenter", isCenter);
		mv.setViewName(view);
		return mv;
	}

	/**
	 * 添加记录执行
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/doAdd")
	public ModelAndView notice_doAdd(HttpServletRequest request, HttpServletResponse response, @Valid NoticeForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/notice/add_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			// 将错误信息Json化
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		
		TblOaNotice coreNotice = form.copyTo();
		//判断是否是总部账号
		UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String siteId = user.getSiteId();
		String centerId = noticeService.selectOfCenter(siteId);
		if(centerId!=null&&"570000".equals(centerId)){
			coreNotice.setToZJ("1");
		}else if(centerId!=null&&"591000".equals(centerId)){
			coreNotice.setToFJ("1");
		}
		int res = noticeService.insertNotice(coreNotice);
		if(res==-1){
			mv.addObject("status", "failed");
			mv.addObject("msg", "请选择发送区域");
			return mv;
		}
		// 推送给手机app
		// pushService.pushNotificationToAll(coreNotice.getTitle(),
		// coreNotice.getContent());
		// 重要信息发送给区域负责人
		if (StringUtils.isNotBlank(form.getIsSendMobile()) && "1".equalsIgnoreCase(form.getIsSendMobile())) {
			if (StringUtils.isNotBlank(form.getMobiles())) {
				smsService.insertSmsList(form);
			}
		}
		mv.addObject("status", "SUCCESS");
		mv.addObject("group", form.getGroup());
		return mv;
	}

	/**
	 * 删除
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @param result
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/doDelete")
	public ModelAndView doDelete(HttpServletRequest request, HttpServletResponse response, NoticeForm form)
			throws Exception {
		String noticeIdStr = form.getNoticeId();
		String realNoticeId = "";
		if (StringUtils.isNotBlank(noticeIdStr)) {
			realNoticeId = EncrypTool.dencode(noticeIdStr);
		}
		int result = noticeService.deleteByNoticeId(realNoticeId);
		Map map = new HashMap<String, String>();
		if (result < 0) {
			map.put("status", "FAILD");
		} else if (result >= 0) {
			map.put("status", "SUCCESS");
		}
		ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
		return mv;
	}

	/**
	 * 编辑页面
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/edit")
	public ModelAndView editNotice(HttpServletRequest request, HttpServletResponse response, NoticeForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView();
		String noticeIdStr = form.getNoticeId();
		String realNoticeId = "";
		if (StringUtils.isNotBlank(noticeIdStr)) {
			realNoticeId = EncrypTool.dencode(noticeIdStr);
		}

		TblOaNotice notice = noticeService.selectNoticeById(new Integer(realNoticeId));
		String view = "";
		String isCenter = "";
		String isZBNotice = "";
		String isZJNotice = "";
		String isFJNotice = "";
		if (Constants.NOTICE_GROUP_NOTICE.equalsIgnoreCase(notice.getNoticeGroup())) {
			view = "/notice/edit_notice";
			//查询员工所属一级中心站点
			UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			String siteId = user.getSiteId();
			if("10000".equals(siteId)){
				isCenter = "1";
			}else{
				String centerId = noticeService.selectOfCenter(siteId);
				if("769000".equals(centerId)){
					isCenter = "1";
				}
			}
			List<String> regions = noticeService.selectRegions(new Integer(realNoticeId));
			//判断公告是浙江的还是总部的
			for(String id:regions){
				if("570000".equals(id)){
					isZJNotice = "1";
				}else if("769000".equals(id)){
					isZBNotice = "1";
				}else if("591000".equals(id)){
					isFJNotice = "1";
				}
			}
			mv.addObject("isCenter", isCenter);
			mv.addObject("isZBNotice", isZBNotice);
			mv.addObject("isZJNotice", isZJNotice);
			mv.addObject("isFJNotice", isFJNotice);
		} else if (Constants.NOTICE_GROUP_DAILY.equalsIgnoreCase(notice.getNoticeGroup())) {
			view = "/notice/edit_daily";
		}
		mv.setViewName(view);
		mv.addObject("notice", notice);
		mv.addObject(Constants.FORM_COMMAND_KEY, form);
		return mv;
	}

	/**
	 * 编辑公告执行
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @param result
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/doEdit")
	public ModelAndView notice_doEidt(HttpServletRequest request, HttpServletResponse response, @Valid NoticeForm form,
			BindingResult result) throws Exception {

		ModelAndView mv = new ModelAndView("/notice/edit_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			// 将错误信息Json化
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		String noticeIdStr = form.getNoticeId();
		String realNoticeId = "";
		if (StringUtils.isNotBlank(noticeIdStr)) {
			realNoticeId = EncrypTool.dencode(noticeIdStr);
		}
		TblOaNotice coreNotice = form.copyTo();
		//判断是否是浙江账号
		UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String siteId = user.getSiteId();
		String centerId = noticeService.selectOfCenter(siteId);
		if(centerId!=null&&"570000".equals(centerId)){
			coreNotice.setToZJ("1");
		}
		if(centerId!=null&&"591000".equals(centerId)){
			coreNotice.setToFJ("1");
		}
		coreNotice.setNoticeId(new Long(realNoticeId));
		int res = noticeService.updateNotice(coreNotice);
		if(res==-1){
			mv.addObject("msg", "请选择发布区域");
			mv.addObject("status", "FAILED");
			return mv;
		}
		mv.addObject("status", "SUCCESS");
		mv.addObject("group", form.getGroup());
		return mv;
	}

	/**
	 * 预览打印
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @param result
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/preview")
	public ModelAndView previce(HttpServletRequest request, HttpServletResponse response, @Valid NoticeForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/notice/preview", Constants.FORM_COMMAND_KEY, form);
		String noticeIdStr = form.getNoticeId();
		if (StringUtils.isNotBlank(noticeIdStr)) {
			TblOaNotice coreNotice = noticeService.selectNoticeById(new Integer(noticeIdStr));
			// 插入读过的记录
			UserInfo user = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			noticeService.insertNoticeRead(coreNotice.getNoticeId() + "", user.getUsername(), coreNotice.getNoticeGroup());
			mv.addObject("coreNotice", coreNotice);
			return mv;
		}
		return null;

	}

	@RequestMapping(value = "/preview4A6")
	public ModelAndView preview4A6(HttpServletRequest request, HttpServletResponse response, @Valid NoticeForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/notice/preview", Constants.FORM_COMMAND_KEY, form);
		if (StringUtils.isBlank(form.getNoticeId())) {
			return null;
		}
		if (StringUtils.isBlank(form.getEmpId())) {
			return null;
		}
		String noticeIdStr = form.getNoticeId();
		String empIdStr = form.getEmpId();

		String noticeId = EncrypTool.dencode(noticeIdStr);
		String empId = EncrypTool.dencode(empIdStr);

		if (StringUtils.isNotBlank(noticeId) && StringUtils.isNotBlank(empId)) {
			TblOaNotice coreNotice = noticeService.selectNoticeById(new Integer(noticeId));
			// 插入读过的记录
			if (null != coreNotice) {
				
				noticeService.insertNoticeRead(coreNotice.getNoticeId() + "", empId, coreNotice.getNoticeGroup());
				mv.addObject("coreNotice", coreNotice);
				return mv;
			} else {
				return null;
			}
		}
		return null;
	}

	/**
	 * 周刊
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/weekly")
	public ModelAndView weekly(HttpServletRequest request, HttpServletResponse response, NoticeForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/notice/weekly_2", Constants.FORM_COMMAND_KEY, form);
		List<TblSiteWeeklyArticle> list = weeklyService.selectLast();
		List<TblSiteWeeklyMap> mapList = weeklyService.selectMapByWeekId(list.get(0).getWeeklyId() + "");
		mv.addObject("article", list.get(0));
		mv.addObject("mapList", mapList);
		mv.addObject("lastWeekly", list);
		mv.addObject("returnType", "weekly");
		return mv;
	}

	/**
	 * 文章
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/weekly/article")
	public ModelAndView weekly_article(HttpServletRequest request, HttpServletResponse response, NoticeForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/notice/weekly_2", Constants.FORM_COMMAND_KEY, form);
		String articleId = form.getArticleId();
		List<TblSiteWeeklyArticle> list = weeklyService.selectLast();
		List<TblSiteWeeklyMap> mapList = weeklyService.selectMapByWeekId(list.get(0).getWeeklyId() + "");
		mv.addObject("mapList", mapList);
		TblSiteWeeklyArticle tblSiteWeeklyArticle = weeklyService.selectWeeklyArticleById(articleId);
		mv.addObject("lastWeekly", list);
		mv.addObject("article", tblSiteWeeklyArticle);
		mv.addObject("returnType", "weekly");
		return mv;
	}

}
